<template>
  <aside class="left-sidebar">
    <!-- Task Sidebar -->
    <div class="task-section">
      <div class="sidebar-header">
        <h4><i class="fas fa-tasks"></i> 计划列表</h4>
        <div class="task-stats">
          <span class="task-count">{{ tasks.length }}</span>
          <span class="task-label">个任务</span>
        </div>
      </div>
      <div class="sidebar-content">
        <div class="task-filters">
          <button 
            class="filter-tag"
            :class="{ active: currentFilter === 'all' }"
            @click="filterTasks('all')"
          >
            <i class="fas fa-list"></i>
            全部 <span class="count">{{ allTasksCount }}</span>
          </button>
          <button 
            class="filter-tag"
            :class="{ active: currentFilter === 'pending' }"
            @click="filterTasks('pending')"
          >
            <i class="fas fa-clock"></i>
            待完成 <span class="count">{{ pendingTasksCount }}</span>
          </button>
          <button 
            class="filter-tag"
            :class="{ active: currentFilter === 'completed' }"
            @click="filterTasks('completed')"
          >
            <i class="fas fa-check"></i>
            已完成 <span class="count">{{ completedTasksCount }}</span>
          </button>
        </div>
        <div class="sidebar-task-list">
          <div 
            v-for="task in filteredTasks" 
            :key="task.id"
            class="sidebar-task-item"
            :class="{ completed: task.status === 'completed' }"
          >
            <div class="task-checkbox">
              <input 
                type="checkbox"
                :checked="task.status === 'completed'"
                @change="toggleTask(task.id)"
              >
            </div>
            <div class="task-content">
              <div class="task-title">{{ task.title }}</div>
              <div class="task-priority" v-if="task.priority">
                <span class="priority-indicator" :class="task.priority"></span>
                {{ task.priority }}
              </div>
            </div>
          </div>
          <div v-if="filteredTasks.length === 0" class="no-tasks">
            <i class="fas fa-inbox"></i>
            <span>暂无任务</span>
          </div>
        </div>
        <div class="sidebar-footer">
          <router-link to="/todolist" class="btn btn-primary btn-compact">
            <i class="fas fa-external-link-alt"></i>
            管理任务
          </router-link>
        </div>
      </div>
    </div>
    
    <!-- Growth Assessment Section -->
    <div class="growth-section" v-if="isUserAdmin()">
      <div class="assessment-header">
        <h4><i class="fas fa-chart-line"></i> 成长评估</h4>
        <div class="current-stats">
          <div class="stat-display">
            <span class="stat-icon"><i class="fas fa-star"></i></span>
            <span class="stat-value">LV.{{ userLevel }}</span>
          </div>
          <div class="stat-display">
            <span class="stat-icon"><i class="fas fa-bolt"></i></span>
            <span class="stat-value">{{ formatNumber(battlePower) }}</span>
          </div>
        </div>
      </div>
      <div class="assessment-content">
        <!-- Level Progress -->
        <div class="level-progress">
          <div class="progress-header">
            <span class="progress-label">升级进度</span>
            <span class="progress-text">{{ formatNumber(currentProgress) }}/{{ nextLevelRequired }}</span>
          </div>
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: progressPercentage + '%' }"></div>
          </div>
          <div class="next-level-info">
            <small>距离 LV.{{ nextLevel }} 还需 {{ formatNumber(pointsNeeded) }} 战斗力</small>
          </div>
        </div>
        
        <!-- Assessment Categories -->
        <div class="assessment-categories">
          <h5>能力评估</h5>
          <div class="category-list">
            <div class="category-item">
              <div class="category-info">
                <i class="fas fa-book"></i>
                <span>内容创作</span>
              </div>
              <span class="category-score">{{ formatNumber(contentScore) }}</span>
            </div>
            <div class="category-item">
              <div class="category-info">
                <i class="fas fa-video"></i>
                <span>视频制作</span>
              </div>
              <span class="category-score">{{ formatNumber(videoScore) }}</span>
            </div>
            <div class="category-item">
              <div class="category-info">
                <i class="fas fa-tasks"></i>
                <span>任务管理</span>
              </div>
              <span class="category-score">{{ formatNumber(taskScore) }}</span>
            </div>
            <div class="category-item">
              <div class="category-info">
                <i class="fas fa-fire"></i>
                <span>学习活跃度</span>
              </div>
              <span class="category-score">{{ formatNumber(activityScore) }}</span>
            </div>
          </div>
        </div>
        
        <!-- Improvement Tips -->
        <div class="improvement-tips">
          <h5><i class="fas fa-lightbulb"></i> 个性化建议</h5>
          <div class="tip-list">
            <div v-for="tip in improvementTips" :key="tip.id" class="tip-item">
              <i :class="tip.icon"></i>
              <span>{{ tip.text }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </aside>
</template>

<script>
export default {
  name: 'AppSidebar',
  props: {
    tasks: {
      type: Array,
      default: () => []
    },
    currentUser: {
      type: Object,
      default: null
    },
    courses: {
      type: Array,
      default: () => []
    },
    videoCourses: {
      type: Array,
      default: () => []
    },
    // 新增props，接收从父组件传递的计算好的统计数据
    totalCourseChapters: {
      type: Number,
      default: 0
    },
    totalVideoChapters: {
      type: Number,
      default: 0
    },
    recentActivity: {
      type: Number,
      default: 0
    }
  },
  emits: ['filter-tasks', 'toggle-task'],
  data() {
    return {
      currentFilter: 'all'
    }
  },
  computed: {
    filteredTasks() {
      switch (this.currentFilter) {
        case 'pending':
          return this.tasks.filter(task => task.status !== 'completed')
        case 'completed':
          return this.tasks.filter(task => task.status === 'completed')
        default:
          return this.tasks.slice(0, 5) // 只显示前5个任务
      }
    },
    allTasksCount() {
      // 总任务数
      return this.tasks.length
    },
    pendingTasksCount() {
      // 待完成任务数
      return this.tasks.filter(task => task.status !== 'completed').length
    },
    completedTasksCount() {
      // 已完成任务数
      return this.tasks.filter(task => task.status === 'completed').length
    },
    userLevel() {
      if (!this.currentUser) return 1
      // 用户等级基于四个维度的平均进度计算
      const levelProgress = this.calculateLevelProgress()
      return Math.floor(levelProgress) + 1
    },
    battlePower() {
      if (!this.currentUser) return 0
      // 优先使用从父组件传递的用户战斗力数据
      if (this.currentUser.battlePower !== undefined) {
        return this.currentUser.battlePower
      }
      // 如果没有，则使用计算的战斗力
      return this.calculateBattlePower()
    },
    currentProgress() {
      // 当前等级进度基于四个维度的平均进度计算
      const levelProgress = this.calculateLevelProgress()
      const progress = (levelProgress % 1) * 100
      // 处理浮点数精度问题，避免出现科学计数法
      return Math.round(progress * 100) / 100
    },
    nextLevelRequired() {
      // 升级所需进度固定为100%
      return 100
    },
    nextLevel() {
      // 下一等级
      const levelProgress = this.calculateLevelProgress()
      return Math.floor(levelProgress) + 2  // 当前等级+1
    },
    pointsNeeded() {
      // 距离下一等级还需进度
      const levelProgress = this.calculateLevelProgress()
      const currentLevel = Math.floor(levelProgress)
      const nextLevelThreshold = (currentLevel + 1) * 0.1  // 每级0.1进度
      const currentProgress = levelProgress
      
      // 计算还需多少进度达到下一级
      const progressNeeded = nextLevelThreshold - currentProgress
      
      // 处理浮点数精度问题，避免出现科学计数法
      const roundedProgressNeeded = Math.max(0, Math.round(progressNeeded * 1000) / 1000)
      
      // 如果结果非常接近0，直接显示0
      return roundedProgressNeeded < 0.001 ? 0 : roundedProgressNeeded
    },
    progressPercentage() {
      // 进度条百分比
      return this.currentProgress
    },
    contentScore() {
      // 内容创作得分 = 笔记课程数量
      return this.courses.length
    },
    videoScore() {
      // 视频制作得分 = 视频课程数量
      return this.videoCourses.length
    },
    taskScore() {
      // 任务管理得分 = 视频章节数量
      return this.totalVideoChapters
    },
    activityScore() {
      // 学习活跃度得分 = 最近活动数量
      return this.recentActivity
    },
    improvementTips() {
      const tips = []
      
      // 每个维度的目标值
      const contentTarget = 10  // 内容创作目标：10个笔记
      const videoTarget = 5     // 视频制作目标：5个视频课程
      const taskTarget = 20     // 任务管理目标：20个视频章节
      const activityTarget = 10 // 学习活跃度目标：10个最近更新
      
      // 内容创作进度低于80%时给出建议
      if (this.contentScore / contentTarget < 0.8) {
        tips.push({
          id: 1,
          icon: 'fas fa-plus-circle',
          text: '创建更多笔记来提升内容创作能力'
        })
      }
      
      // 视频制作进度低于80%时给出建议
      if (this.videoScore / videoTarget < 0.8) {
        tips.push({
          id: 2,
          icon: 'fas fa-video',
          text: '尝试制作视频课程来提升技能'
        })
      }
      
      // 任务管理进度低于80%时给出建议
      if (this.taskScore / taskTarget < 0.8) {
        tips.push({
          id: 3,
          icon: 'fas fa-tasks',
          text: '制作更多视频章节来提升执行力'
        })
      }
      
      // 学习活跃度进度低于80%时给出建议
      if (this.activityScore / activityTarget < 0.8) {
        tips.push({
          id: 4,
          icon: 'fas fa-fire',
          text: '保持定期更新来提升活跃度'
        })
      }
      
      return tips.slice(0, 3) // 最多显示3个建议
    }
  },
  methods: {
    filterTasks(filter) {
      this.currentFilter = filter
      this.$emit('filter-tasks', filter)
    },
    toggleTask(taskId) {
      // 立即更新UI以提供即时反馈
      const taskIndex = this.tasks.findIndex(task => task.id === taskId);
      if (taskIndex !== -1) {
        // 创建响应式更新
        this.$emit('toggle-task', taskId);
      }
    },
    calculateBattlePower() {
      // 总战斗力计算公式（降低升级难度）：
      // 内容创作得分 * 10 + 视频制作得分 * 15 + 任务管理得分 * 3 + 学习活跃度得分 * 5
      return this.contentScore * 10 + this.videoScore * 15 + this.taskScore * 3 + this.activityScore * 5
    },
    // 新增方法：计算等级进度（基于四个维度）
    calculateLevelProgress() {
      // 每个维度的目标值
      const contentTarget = 10  // 内容创作目标：10个笔记
      const videoTarget = 5     // 视频制作目标：5个视频课程
      const taskTarget = 20     // 任务管理目标：20个视频章节
      const activityTarget = 10 // 学习活跃度目标：10个最近更新
      
      // 计算每个维度的进度（0-1之间）
      const contentProgress = Math.min(this.contentScore / contentTarget, 1)
      const videoProgress = Math.min(this.videoScore / videoTarget, 1)
      const taskProgress = Math.min(this.taskScore / taskTarget, 1)
      const activityProgress = Math.min(this.activityScore / activityTarget, 1)
      
      // 计算平均进度
      const averageProgress = (contentProgress + videoProgress + taskProgress + activityProgress) / 4
      
      // 将平均进度转换为等级（每级对应0.1的进度范围）
      return averageProgress * 10  // 最多10级
    },
    // 新增方法：格式化数字，避免科学计数法
    formatNumber(value) {
      if (value === null || value === undefined) return '0'
      // 处理极小的数值
      if (Math.abs(value) < 1e-10) return '0'
      // 保留两位小数
      return parseFloat(value.toFixed(2))
    },
    // 新增方法：检查用户是否为管理员
    isUserAdmin() {
      return this.currentUser && this.currentUser.role === 'admin'
    }
  }
}
</script>

<style scoped>
.left-sidebar {
  width: 300px;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.task-section, .growth-section {
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  overflow: hidden;
}

.sidebar-header, .assessment-header {
  padding: 1rem;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sidebar-header h4, .assessment-header h4 {
  font-size: 12px;
  font-weight: 600;
  color: #1e293b;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.task-stats {
  font-size: 11px;
  color: #64748b;
}

.task-count {
  font-weight: 600;
  color: #1e293b;
}

.sidebar-content, .assessment-content {
  padding: 1rem;
}

.task-filters {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  margin-bottom: 1rem;
}

.filter-tag {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.5rem;
  border: none;
  background: #f8fafc;
  border-radius: 6px;
  font-size: 11px;
  cursor: pointer;
  transition: all 0.2s ease;
  color: #64748b;
}

.filter-tag:hover {
  background: #f1f5f9;
}

.filter-tag.active {
  background: #3b82f6;
  color: white;
}

.count {
  background: rgba(255, 255, 255, 0.2);
  padding: 0.125rem 0.375rem;
  border-radius: 12px;
  font-size: 10px;
  font-weight: 600;
}

.filter-tag.active .count {
  background: rgba(255, 255, 255, 0.3);
}

.sidebar-task-list {
  max-height: 200px;
  overflow-y: auto;
  margin-bottom: 1rem;
}

.sidebar-task-item {
  display: flex;
  align-items: flex-start;
  gap: 0.5rem;
  padding: 0.5rem 0;
  border-bottom: 1px solid #f1f5f9;
}

.sidebar-task-item:last-child {
  border-bottom: none;
}

.sidebar-task-item.completed {
  opacity: 0.6;
}

.task-checkbox input {
  margin: 0;
}

.task-content {
  flex: 1;
  min-width: 0;
}

.task-title {
  font-size: 11px;
  color: #1e293b;
  font-weight: 500;
  margin-bottom: 0.25rem;
  word-break: break-word;
}

.task-priority {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  font-size: 10px;
  color: #64748b;
}

.priority-indicator {
  width: 6px;
  height: 6px;
  border-radius: 50%;
}

.priority-indicator.high {
  background: #ef4444;
}

.priority-indicator.medium {
  background: #f59e0b;
}

.priority-indicator.low {
  background: #10b981;
}

.no-tasks {
  text-align: center;
  padding: 2rem 1rem;
  color: #64748b;
  font-size: 11px;
}

.no-tasks i {
  display: block;
  font-size: 24px;
  margin-bottom: 0.5rem;
  opacity: 0.5;
}

.sidebar-footer {
  border-top: 1px solid #e2e8f0;
  padding: 1rem;
}

.btn-compact {
  width: 100%;
  padding: 0.5rem;
  justify-content: center;
}

.btn-primary {
  background: #3b82f6;
  color: white;
  border: 1px solid #3b82f6;
  text-decoration: none;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  border-radius: 6px;
  font-size: 11px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.btn-primary:hover {
  background: #2563eb;
  border-color: #2563eb;
}

/* Growth Assessment Styles */
.current-stats {
  display: flex;
  gap: 1rem;
}

.stat-display {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  font-size: 11px;
  font-weight: 600;
}

.stat-icon i {
  color: #fbbf24;
}

.stat-icon i.fa-bolt {
  color: #3b82f6;
}

.level-progress {
  margin-bottom: 1.5rem;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
  font-size: 11px;
}

.progress-label {
  font-weight: 600;
  color: #1e293b;
}

.progress-text {
  color: #64748b;
}

.progress-bar {
  width: 100%;
  height: 6px;
  background: #e2e8f0;
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #3b82f6, #8b5cf6);
  transition: width 0.3s ease;
}

.next-level-info {
  margin-top: 0.5rem;
  text-align: center;
}

.next-level-info small {
  font-size: 10px;
  color: #64748b;
}

.assessment-categories h5, .improvement-tips h5 {
  font-size: 11px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 0.75rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.category-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  margin-bottom: 1.5rem;
}

.category-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem;
  background: #f8fafc;
  border-radius: 6px;
}

.category-info {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 10px;
  color: #64748b;
}

.category-score {
  font-size: 10px;
  font-weight: 600;
  color: #1e293b;
}

.tip-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.tip-item {
  display: flex;
  align-items: flex-start;
  gap: 0.5rem;
  padding: 0.5rem;
  background: #fef3c7;
  border-radius: 6px;
  font-size: 10px;
  color: #92400e;
}

.tip-item i {
  margin-top: 0.125rem;
  flex-shrink: 0;
}

@media (max-width: 768px) {
  .left-sidebar {
    width: 100%;
  }
}
</style>